<template>
  <div class="user-contest">
    <el-card>
      <div slot="header" class="clearfix">
        <span>参赛报名</span>
      </div>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <!-- 已有报名信息 -->
      <div v-else-if="contestantInfo" class="info-card">
        <el-descriptions title="我的参赛信息" :column="2" border>
          <el-descriptions-item label="真实姓名">{{ contestantInfo.realName }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ maskIdCard(contestantInfo.idCard) }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ maskPhone(contestantInfo.phone) }}</el-descriptions-item>
          <el-descriptions-item label="电子邮箱">{{ contestantInfo.email }}</el-descriptions-item>
          <el-descriptions-item label="联系地址">{{ contestantInfo.address }}</el-descriptions-item>
          <el-descriptions-item label="参赛类型">{{ getContestTypeText(contestantInfo.contestType) }}</el-descriptions-item>
          <el-descriptions-item label="作品集标题">{{ contestantInfo.workTitle }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusTagType(contestantInfo.status)">
              {{ getStatusText(contestantInfo.status) }}
            </el-tag>
          </el-descriptions-item>
          
          <el-descriptions-item v-if="contestantInfo.status === 2" label="拒绝原因" :span="2">
            {{ contestantInfo.rejectReason || '无' }}
          </el-descriptions-item>
          
          <el-descriptions-item label="作品集描述" :span="2">
            {{ contestantInfo.workDescription || '无' }}
          </el-descriptions-item>
          
          <el-descriptions-item label="报名时间" :span="2">
            {{ formatDateTime(contestantInfo.createTime) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="action-buttons" v-if="contestantInfo.status !== 1">
          <el-button type="primary" @click="showEditForm">修改信息</el-button>
          <el-button type="danger" @click="cancelContest">取消报名</el-button>
        </div>
        
        <div class="action-buttons" v-else>
          <el-alert
            title="您的参赛申请已审核通过，现在可以上传您的参赛作品了"
            type="success"
            :closable="false"
            show-icon>
          </el-alert>
          <el-button type="primary" @click="$router.push('/user/photos')">上传作品</el-button>
        </div>
      </div>
      
      <!-- 未报名，显示报名表单 -->
      <div v-else>
        <div class="contest-intro">
          <h3>参赛须知</h3>
          <p>1. 参赛者需要提供真实个人信息，我们将对您的信息严格保密。</p>
          <p>2. 参赛作品必须为原创，严禁抄袭、剽窃他人作品。</p>
          <p>3. 参赛作品将由专业评委进行评审，评审结果将在平台公布。</p>
          <p>4. 获奖作品将有机会参加线下展览并获得丰厚奖品。</p>
          <p>5. 审核通过后，您可以在"我的作品"中上传参赛作品。</p>
        </div>
        
        <el-divider content-position="center">填写报名信息</el-divider>
        
        <el-form
          ref="contestForm"
          :model="formData"
          :rules="rules"
          label-width="100px"
          class="contest-form">
          <el-form-item label="真实姓名" prop="realName">
            <el-input v-model="formData.realName" placeholder="请输入真实姓名"></el-input>
          </el-form-item>
          
          <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="formData.idCard" placeholder="请输入18位身份证号"></el-input>
          </el-form-item>
          
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="formData.phone" placeholder="请输入手机号码"></el-input>
          </el-form-item>
          
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="formData.email" placeholder="请输入电子邮箱"></el-input>
          </el-form-item>
          
          <el-form-item label="联系地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入详细联系地址"></el-input>
          </el-form-item>
          
          <el-form-item label="参赛类型" prop="contestType">
            <el-radio-group v-model="formData.contestType">
              <el-radio :label="1">手机摄影</el-radio>
              <el-radio :label="2">相机摄影</el-radio>
              <el-radio :label="3">两者都参加</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="作品集标题" prop="workTitle">
            <el-input v-model="formData.workTitle" placeholder="请输入您的作品集标题"></el-input>
          </el-form-item>
          
          <el-form-item label="作品集描述" prop="workDescription">
            <el-input
              type="textarea"
              :rows="4"
              v-model="formData.workDescription"
              placeholder="请简要描述您的参赛作品集">
            </el-input>
          </el-form-item>
          
          <el-form-item>
            <el-checkbox v-model="agreement">我已阅读并同意比赛规则和隐私条款</el-checkbox>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm" :loading="submitting" :disabled="!agreement">
              提交报名
            </el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <!-- 编辑参赛信息对话框 -->
    <el-dialog title="修改参赛信息" :visible.sync="editDialogVisible" width="600px">
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-width="100px">
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="editForm.realName" placeholder="请输入真实姓名"></el-input>
        </el-form-item>
        
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="editForm.idCard" placeholder="请输入18位身份证号"></el-input>
        </el-form-item>
        
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入电子邮箱"></el-input>
        </el-form-item>
        
        <el-form-item label="联系地址" prop="address">
          <el-input v-model="editForm.address" placeholder="请输入详细联系地址"></el-input>
        </el-form-item>
        
        <el-form-item label="参赛类型" prop="contestType">
          <el-radio-group v-model="editForm.contestType">
            <el-radio :label="1">手机摄影</el-radio>
            <el-radio :label="2">相机摄影</el-radio>
            <el-radio :label="3">两者都参加</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="作品集标题" prop="workTitle">
          <el-input v-model="editForm.workTitle" placeholder="请输入您的作品集标题"></el-input>
        </el-form-item>
        
        <el-form-item label="作品集描述" prop="workDescription">
          <el-input
            type="textarea"
            :rows="4"
            v-model="editForm.workDescription"
            placeholder="请简要描述您的参赛作品集">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit" :loading="submitting">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'UserContest',
  data() {
    // 身份证号验证
    const validateIdCard = (rule, value, callback) => {
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (!reg.test(value)) {
        return callback(new Error('请输入正确的身份证号码'))
      }
      callback()
    }
    
    // 手机号验证
    const validatePhone = (rule, value, callback) => {
      const reg = /^1[3-9]\d{9}$/
      if (!reg.test(value)) {
        return callback(new Error('请输入正确的手机号码'))
      }
      callback()
    }
    
    return {
      loading: false,
      submitting: false,
      contestantInfo: null,
      agreement: false,
      formData: {
        realName: '',
        idCard: '',
        phone: '',
        email: '',
        address: '',
        contestType: 1,
        workTitle: '',
        workDescription: '',
        userId: ''
      },
      rules: {
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: validateIdCard, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入电子邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入联系地址', trigger: 'blur' },
          { max: 200, message: '地址不能超过200个字符', trigger: 'blur' }
        ],
        contestType: [
          { required: true, message: '请选择参赛类型', trigger: 'change' }
        ],
        workTitle: [
          { required: true, message: '请输入作品集标题', trigger: 'blur' },
          { max: 50, message: '标题不能超过50个字符', trigger: 'blur' }
        ],
        workDescription: [
          { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {
        id: '',
        realName: '',
        idCard: '',
        phone: '',
        email: '',
        address: '',
        contestType: 1,
        workTitle: '',
        workDescription: ''
      }
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  created() {
    this.formData.userId = this.userId
    this.fetchContestantInfo()
  },
  methods: {
    async fetchContestantInfo() {
      this.loading = true
      try {
        const res = await this.$http.get(`/contestants/user/${this.userId}`)
        if (res.data.code === 1) {
          this.contestantInfo = res.data.data
        }
      } catch (error) {
        console.error('获取参赛信息失败', error)
      } finally {
        this.loading = false
      }
    },
    submitForm() {
      if (!this.agreement) {
        this.$message.warning('请先阅读并同意比赛规则和隐私条款')
        return
      }
      
      this.$refs.contestForm.validate(async valid => {
        if (valid) {
          this.submitting = true
          try {
            const res = await this.$http.post('/contestants', this.formData)
            if (res.data.code === 1) {
              this.$message.success('报名成功，请等待审核')
              this.fetchContestantInfo()
            } else {
              this.$message.error(res.data.msg || '报名失败')
            }
          } catch (error) {
            console.error('报名失败', error)
            this.$message.error('报名失败，请稍后重试')
          } finally {
            this.submitting = false
          }
        } else {
          return false
        }
      })
    },
    resetForm() {
      this.$refs.contestForm.resetFields()
      this.agreement = false
    },
    showEditForm() {
      this.editForm = {
        id: this.contestantInfo.id,
        realName: this.contestantInfo.realName,
        idCard: this.contestantInfo.idCard,
        phone: this.contestantInfo.phone,
        email: this.contestantInfo.email,
        address: this.contestantInfo.address,
        contestType: this.contestantInfo.contestType,
        workTitle: this.contestantInfo.workTitle,
        workDescription: this.contestantInfo.workDescription
      }
      this.editDialogVisible = true
    },
    submitEdit() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          this.submitting = true
          try {
            const res = await this.$http.put('/contestants', this.editForm)
            if (res.data.code === 1) {
              this.$message.success('修改成功')
              this.editDialogVisible = false
              this.fetchContestantInfo()
            } else {
              this.$message.error(res.data.msg || '修改失败')
            }
          } catch (error) {
            console.error('修改失败', error)
            this.$message.error('修改失败，请稍后重试')
          } finally {
            this.submitting = false
          }
        } else {
          return false
        }
      })
    },
    cancelContest() {
      this.$confirm('确定要取消报名吗？该操作不可恢复', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const res = await this.$http.delete(`/contestants/${this.contestantInfo.id}`)
          if (res.data.code === 1) {
            this.$message.success('取消报名成功')
            this.contestantInfo = null
          } else {
            this.$message.error(res.data.msg || '取消报名失败')
          }
        } catch (error) {
          console.error('取消报名失败', error)
          this.$message.error('取消报名失败')
        }
      }).catch(() => {})
    },
    getContestTypeText(type) {
      const typeMap = {
        1: '手机摄影',
        2: '相机摄影',
        3: '两者都参加'
      }
      return typeMap[type] || '未知'
    },
    getStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '已通过',
        2: '已拒绝'
      }
      return statusMap[status] || '未知'
    },
    getStatusTagType(status) {
      const typeMap = {
        0: 'warning',
        1: 'success',
        2: 'danger'
      }
      return typeMap[status] || 'info'
    },
    formatDateTime(time) {
      if (!time) return ''
      const date = new Date(time)
      return date.toLocaleString()
    },
    maskIdCard(idCard) {
      if (!idCard) return ''
      return idCard.replace(/(\d{6})(\d{8})(\d{4})/, '$1********$3')
    },
    maskPhone(phone) {
      if (!phone) return ''
      return phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
    }
  }
}
</script>

<style scoped>
.user-contest {
  padding: 20px;
}

.loading-container {
  padding: 20px 0;
}

.contest-intro {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
}

.contest-intro h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
  color: #409EFF;
}

.contest-intro p {
  margin: 8px 0;
  font-size: 14px;
  line-height: 1.5;
}

.contest-form {
  max-width: 600px;
  margin: 0 auto;
}

.info-card {
  padding: 10px;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
}

.el-descriptions {
  margin-bottom: 20px;
}
</style> 